package com.RequstHttpUtil;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class NewHttp {
    /**
     * HttpURLConnection
     * @param posturl
     * @param postData
     * @return
     */
    public String Post(String posturl,String postData) {
        StringBuilder response = null;
        try {
            URL url = new URL(posturl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json"); // 设置请求头，根据实际情况调整
            conn.setDoOutput(true);

            // 构建POST数据
            byte[] postDataBytes = postData.getBytes("UTF-8");

            // 发送POST数据
            try (OutputStream os = conn.getOutputStream()) {
                os.write(postDataBytes);
                os.flush();
            } catch (Exception e) {
                System.out.println("发生Post数据出错");
                e.printStackTrace();
            }

            // 读取服务器返回的响应
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            } catch (Exception e) {
                System.out.println();
                e.printStackTrace();
            }
            conn.disconnect();
        } catch (Exception e) {
            System.out.println("调用POST接口发生错误");
            e.printStackTrace();
        }
        return response.toString();
    }


}
